import storage from 'src/utils/storage';
import API from './repository/addresses';

/**
 * localStorage 的key
 * @type {string}
 */
const AddressKey = 'ak';

/**
 * 检查地区缓存是否需要更新
 * @returns {*}
 */
const checkNeedUpdate = function () {
    let list = storage.get(AddressKey);
    return !list || list.length === 0;
};

/**
 * 更新本地字典
 */
const update = function () {
    return new Promise((resolve, reject) => {
        if (checkNeedUpdate()) {
            API.fetchAll()
                .then(res => {
                    let list = res;
                    storage.set(AddressKey, list);
                    resolve(list);
                })
                .catch(err => {
                    reject(err);
                });
        } else {
            resolve(getAll());
        }
    });
};

/**
 * 获取所有条目
 * @returns {*|Array}
 */
const getAll = function () {
    return storage.get(AddressKey) || [];
};

/**
 * 通过code获取地址条目
 * @returns {*}
 */
const getAddress = function (code) {
    return getAll().find(item => item.code === code);
};

/**
 * 替换地址code
 */
const replace = function (code) {
    let address = getAddress(code);
    if (address == null) {
        return '未知';
    }
    return address.name;
};

/**
 * 获取级联条目
 * @param code
 */
const getCascade = function (code) {
    if (!code) {
        return;
    }
    let address = getAddress(code);
    // 判断是否有父节点
    if (address && address.parentCode && address.parentCode !== '0') {
        address.parent = getCascade(address.parentCode);
    }
    return address;
};

/**
 * 获取级联的名称array
 * @param code
 * @returns {*}
 */
const getCascadeArray = function (code) {
    let address = getCascade(code);
    if (address) {
        return [address.parent.parent.name, address.parent.name, address.name];
    } else {
        return [];
    }
};

/**
 * 获取树形结构
 * 省份-城市-县区
 * 和后代定义的结构有关
 */
const getTree = function () {
    // 取出省份，即parentCode为0的条目
    let all = storage.get(AddressKey);
    // 将地区分类
    let provinces = [];
    let cities = [];
    let countries = [];
    all.forEach(item => {
        if (item.code.length === 2) {
            provinces.push({
                ...item,
                children: []
            });
        } else if (item.code.length === 4) {
            cities.push({
                ...item,
                children: []
            });
        } else {
            countries.push(item);
        }
    });
    // 将区分配至市
    countries.forEach(item => {
        // 匹配的市
        let right = cities.find(city => city.code === item.parentCode);
        if (right) {
            right.children.push(item);
        }
    });
    // 将市分配至省
    cities.forEach(city => {
        let right = provinces.find(province => province.code === city.parentCode);
        if (right) {
            right.children.push(city);
        }
    });
    return provinces;
};
/**
 * 清理地址缓存
 */
const clearAddressCache = function() {
    storage.remove(AddressKey);
};

export default {
    replace,
    update,
    getCascade,
    getCascadeArray,
    checkNeedUpdate,
    getAddress,
    getAll,
    getTree,
    clearAddressCache
};